#include	"lp_global_vars.h"

int setsock_nonblock(int fd) {
	int flags;

	flags = fcntl(fd, F_GETFL);
	if (flags < 0)
		return flags;
	flags |= O_NONBLOCK;
	if (fcntl(fd, F_SETFL, flags) < 0)
		return -1;

	return 0;
}
//------------------------------------------------------------------------------
int create_tcp_client_socket(const char *ip, int port) {
	struct sockaddr_in server_addr;
	int activate = 1;
	int e = -1;
	int sid;
	memset(&server_addr, '\0', sizeof(struct sockaddr_in));

	sid = socket(AF_INET, SOCK_STREAM, 0);

	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(ip);
	server_addr.sin_port = htons(port);

	while (e < 0) {
		e = connect(sid, (struct sockaddr*) &server_addr, sizeof(struct sockaddr));
		if (e >= 0) {
//			setsock_nonblock(sid);
			break;
		}
		close(sid);
		sleep(1);
		sid = socket(AF_INET, SOCK_STREAM, 0);
	}
	setsockopt(sid, SOL_SOCKET, SO_REUSEADDR, &activate, sizeof(int));
	return sid;
}
//------------------------------------------------------------------------------
int create_tcp_server_socket(const char *ip, int port) {

	struct sockaddr_in server_addr, client_addr;
	int sid, e, activate = 1;
	unsigned int client_addr_len;

	client_addr_len = sizeof(client_addr);
	sid = socket(AF_INET, SOCK_STREAM, 0);
	setsockopt(sid, SOL_SOCKET, SO_REUSEADDR, &activate, sizeof(int));

	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(ip);
	server_addr.sin_port = htons(port);

	e = bind(sid, (struct sockaddr*) &server_addr, sizeof(struct sockaddr));
	assert(e >= 0);
	e = listen(sid, 1);

	printf("Server: PID: L: %d P: %d Waiting for connection requests from predecessor...\n", learnerID, proposerID);
	int new_sid = accept(sid, (struct sockaddr*) &client_addr, &client_addr_len);
	printf("connection request came from the node on	socket: %d\n", new_sid);
	setsockopt(new_sid, SOL_SOCKET, SO_REUSEADDR, &activate, sizeof(int));

//	setsock_nonblock(new_sid);
	return new_sid;
}

